package vip.aster.tenant.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import vip.aster.framework.mybatis.config.MybatisPlusConfig;
import vip.aster.tenant.handler.AsterTenantLineHandler;
import vip.aster.tenant.properties.TenantProperties;

import java.util.ArrayList;
import java.util.List;

/**
 * TenantConfig
 *
 * @author Aster
 * @since 2024/3/22 17:39
 */
@EnableConfigurationProperties(TenantProperties.class)
@AutoConfiguration(after = {MybatisPlusConfig.class})
@ConditionalOnProperty(value = "tenant.enable", havingValue = "true")
public class TenantConfig {

    /**
     * 初始化租户配置
     */
    @Bean
    public boolean initTenant(MybatisPlusInterceptor mybatisPlusInterceptor,
                              TenantProperties tenantProperties) {
        // 多租户插件 必须放到第一位
        if (tenantProperties.getEnable()) {
            List<InnerInterceptor> interceptors = new ArrayList<>();
            interceptors.add(tenantLineInnerInterceptor(tenantProperties));
            interceptors.addAll(mybatisPlusInterceptor.getInterceptors());
            mybatisPlusInterceptor.setInterceptors(interceptors);
        }
        return true;
    }

    /**
     * 多租户插件
     */
    public TenantLineInnerInterceptor tenantLineInnerInterceptor(TenantProperties tenantProperties) {
        return new TenantLineInnerInterceptor(new AsterTenantLineHandler(tenantProperties));
    }
}
